package com.wly.ui.scene
{
	import com.wly.event.EventCodes;
	import com.wly.event.EventManager;
	import com.wly.sound.SoundManager;
	import com.wly.ui.gamescene.GameScene;
	import com.wly.ui.gamescene.PlayScene;
	
	import flash.display.Sprite;
	import flash.utils.Dictionary;
	
	public class SceneManager extends Sprite
	{
		private var _sceneDic:Dictionary = new Dictionary();
		private var _curScene:SceneBase;
		
		public function SceneManager()
		{
			super();
		}
		
		public function init():void
		{
			EventManager.getInstance().registerEvent(EventCodes.EVENT_SCENE_UPDATE, onSceneUpdate);
			
			registerScene(SceneDefine.SCENE_WELCOME, WelcomeScene);
			registerScene(SceneDefine.SCENE_PLAY, PlayScene);
			registerScene(SceneDefine.SCENE_GAME, GameScene);
			SoundManager.instance.init();
			
			gotoDefaultScene();
		}
		
		private function onSceneUpdate(e:*):void
		{
			var newSceneId:int = e as int;
			gotoScene(newSceneId);
		}
		
		public function registerScene(sceneId:int, sceneClass:Class):void
		{
			_sceneDic[sceneId] = sceneClass;
		}
		
		public function gotoDefaultScene():void
		{
			gotoScene(SceneDefine.SCENE_WELCOME);
		}
		
		public function gotoScene(sceneId:int):void
		{
			if(_sceneDic[sceneId] == null)
			{
				trace(this, "unknown sceneid:", sceneId);
				return;
			}
			if(_curScene)
			{
				_curScene.destroyScene();
				removeChild(_curScene);
				_curScene = null;
			}
			
			var sceneClass:Class = _sceneDic[sceneId] as Class;
			_curScene = new sceneClass() as SceneBase;
			addChild(_curScene);
			_curScene.initScene();
			if(_curScene is GameScene)
			{
				addChild((_curScene as GameScene).debugSprite);
			}
		}
	}
}